<?php

namespace App\Models;

use App\Services\CommonService;
use App\Services\GoodsService;
use App\Services\OrderService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class OrderLease extends Model
{
    use HasFactory;
    protected $table = 'sp_order_lease_2';
    protected $primaryKey = 'id';
    public $timestamps = false;

    //账单状态
    const ORDER_LEASE_STATUS_NOPAY = 0;//未支付
    const ORDER_LEASE_STATUS_PAID = 1;//已支付
    const ORDER_LEASE_STATUS_REFUNDED = 2;//已退款
    const ORDER_LEASE_STATUS_BUYOUT = 3;//已买断
    const ORDER_LEASE_STATUS_OVERDUE = 4;//已逾期
    const ORDER_LEASE_STATUS_OFFLINEPAY = 5;//线下支付


    const ORDER_LEASE_STATUS_LIST = [
        '0' => '未支付',
        '1' => '已支付',
        '2' => '已退款',
        '3' => '已买断',
        '4' => '已逾期',
        '5' => '线下支付',
    ];

    const LEASE_PAY_TYPE_ANTCHAIN = 1;//智能合同代扣
    const LEASE_PAY_TYPE_ZM = 2;//芝麻信用
    const LEASE_PAY_TYPE_HUABEI = 3;//花呗
    const LEASE_PAY_TYPE_PREPAYMENT = 4;//主动支付
    const LEASE_PAY_TYPE_OFFLINE = 5;//线下支付
    const LEASE_PAY_TYPE_REPLACE = 6;//代付
    const PAY_TYPE_YIFUBAO=7;//易付宝
    const LEASE_PAY_TYPE_WECHAT=8;//微信支付

    const ORDER_LEASE_PAY_TYPE_LIST = [
        1 => '智能合同代扣',
        2 => '预授权代扣',
        3 => '花呗分期',
        4 => '主动支付',
        5 => '线下支付',
        6 => '代付',
        7 => '易付宝',
        8 => '微信支付',
    ];

    const LEASE_WITHHOLD_STATUS_NO = 1;//代扣开关 打开
    const LEASE_WITHHOLD_STATUS_OFF = 2;//代扣开关 关闭

    const ORDER_LEASE_SETTLE_STATUS_NO = 0;//未结算
    const ORDER_LEASE_SETTLE_STATUS_YES = 1;//已结算
    const ORDER_LEASE_SETTLE_STATUS_REFUSE = 2;//拒绝结算
    const ORDER_LEASE_SETTLE_STATUS_REFUND = 3;//结算已退款

    const ORDER_LEASE_SETTLE_STATUS_LIST = [
        '0' => '未结算',
        '1' => '已结算',
        '2' => '拒绝结算',
        '3' => '结算已退款',
    ];

    const ORDER_LEASE_OVERDUE_SEND_NO = 1;//逾期短信 未发送
    const ORDER_LEASE_OVERDUE_SEND_YES = 2;//逾期短信 已发送

    const ORDER_LEASE_OVERDUE_SEND_LIST = [
        '1' => '未发送',
        '2' => '已发送'
    ];
    protected function createManageOrderLease($order,$is_haubei,$alipay_trade_no,$down_payment=0){
        if(!$down_payment>0){
            $down_payment=0;
        }
        if($this->where('order_id',$order['id'])->count() == 0){
            if($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_DAY){//按天租赁
                if($order['lease_time'] < 30){
                    $which_period = $order['lease_time'];
                    $begin = strtotime($order['begin_time']);
                    $begin_time = strtotime("+$which_period day",$begin);
                    $data[0]['order_id'] = $order['id'];
                    $data[0]['which_period'] = 1;
                    $data[0]['begin_time'] = $begin_time;
                    $data[0]['end_time'] = $begin_time+$order['lease_time']*24*3600;
                    $data[0]['rent'] = sprintf("%.2f",$order['lease_price'] * $order['lease_time']*$order['amount']+$down_payment);
                    $data[0]['create_time'] = time();
                    $data[0]['paid_rent'] = 0;
                    $data[0]['pay_type'] = $order['pay_type'];
                    if($is_haubei == GoodsService::GOODS_SETMEAL_IS_HUABEI){//花呗
                        $data[0]['pay_time'] = time();
                        $data[0]['status']   = OrderLease::ORDER_LEASE_STATUS_PAID;
                        $data[0]['alipay_trade_no'] =$alipay_trade_no;
                        $data[0]['trade_no'] =$alipay_trade_no;
                        $data[0]['paid_rent'] = sprintf("%.2f",$order['lease_price'] * $order['lease_time']*$order['amount']);
                    }
                }else{
                    for ($i=0;$i<$order['month_total'];$i++){
                        if($i+1 == ceil($order['lease_time']/30)){
//                          源代码有bug  $rent_day = $order['lease_time']%30;
                            $rent_day = $order['lease_time']-$i*30;
                        }else{
                            $rent_day = 30;
                        }

//                        $which_period = $i*30;
//                        $begin = strtotime($order['begin_time']) + ($which_period)*3600*24;

//                        $order['begin_time']='2023-01-30';
                        $which_period = $i;
                        $beginD=date('d',strtotime($order['begin_time']));
                        if($beginD>28){
                            $beginm_time=date('Y-m',strtotime($order['begin_time']));
                            $beginM=date('m',strtotime('+'.$i.'month',strtotime($beginm_time)));
                            $beginY=date('Y',strtotime('+'.$i.'month',strtotime($beginm_time)));

                            if($beginM=='02'&&$beginD>28){     //2月份最后一天
                                $begin_time = strtotime($beginY.'-'.$beginM.'-28');
                            }else if(in_array($beginM,['04','06','09','11'])&&$beginD>30){ //30天的最后一天
                                $begin_time = strtotime($beginY.'-'.$beginM.'-30');
                            }else{
                                $begin = strtotime('+'.$i.'month',strtotime($order['begin_time']));
                                $begin_time = strtotime(date('Y-m-d',$begin));
                            }
                        }else{
                            $begin = strtotime('+'.$i.'month',strtotime($order['begin_time']));
                            $begin_time = strtotime(date('Y-m-d',$begin));
                        }

                        $data[$i]['order_id'] = $order['id'];
                        $data[$i]['which_period'] = $i+1;
                        $data[$i]['begin_time'] = $begin_time;
                        $data[$i]['end_time'] = $begin_time+$which_period+$rent_day*24*3600;
                        if($i==0){
                            $data[$i]['rent'] = sprintf("%.2f",$down_payment);
                        }else{
                            $data[$i]['rent'] = sprintf("%.2f",$order['lease_price']*$order['amount']);
                        }
                        $data[$i]['create_time'] = time();
                        $data[$i]['paid_rent'] = 0;
                        $data[$i]['pay_type'] = $order['pay_type'];
                        if($is_haubei == GoodsService::GOODS_SETMEAL_IS_HUABEI){//花呗
                            $data[$i]['pay_time'] = time();
                            $data[$i]['status']   = OrderLease::ORDER_LEASE_STATUS_PAID;
                            $data[$i]['alipay_trade_no'] =$alipay_trade_no;
                            $data[$i]['trade_no'] =$alipay_trade_no;
                            $data[$i]['paid_rent'] = sprintf("%.2f",$order['lease_price']*$rent_day*$order['amount']);
                        }
                    }
                }
            }elseif($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_MONTH){//按月租赁
                for ($i=0;$i<$order['month_total'];$i++){
                    $begin_time = strtotime(date('Y-m-d',strtotime("+$i months",strtotime($order['begin_time']))));
                    $data[$i]['order_id'] = $order['id'];
                    $data[$i]['which_period'] = $i+1;
                    $data[$i]['begin_time'] = $begin_time;
                    $data[$i]['end_time'] = strtotime("+1 months", $begin_time);
                    if($i==0){
                        $data[$i]['rent'] = sprintf("%.2f",$down_payment);
                    }else{
                        $data[$i]['rent'] = sprintf("%.2f",$order['lease_price']*$order['amount']);
                    }
                    $data[$i]['paid_rent'] = 0;
                    $data[$i]['create_time'] = time();
                    $data[$i]['pay_type'] = $order['pay_type'];
                    if($is_haubei == GoodsService::GOODS_SETMEAL_IS_HUABEI){//花呗
                        $data[$i]['pay_time'] = time();
                        $data[$i]['status']   = OrderLease::ORDER_LEASE_STATUS_PAID;
                        $data[$i]['alipay_trade_no'] =$alipay_trade_no;
                        $data[$i]['trade_no'] =$alipay_trade_no;
                        $data[$i]['paid_rent'] = sprintf("%.2f",$order['lease_price']*$order['amount']);
                    }
                }
            }elseif($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_CUSTOM){//自定义租期
                $lease = GoodsCustomRent::where([['goods_id',$order['goods_id']],['setmeal_id',$order['setmeal_id']],['spec_id',$order['spec_id']],['is_delete',CommonService::GOODS_IS_DELETE_NOT]])->select('id','spec_id','which_period','lease_days','withhold_cycle','lease_price')->get();
                $lease = $lease ? $lease->toArray() : [];
                if(!empty($lease)){
                    foreach ($lease as $k=>$v){
                        $lease_days = $v['lease_days'];
                        $base = $k * $lease_days;
                        $begin_time = strtotime(date('Y-m-d',strtotime("+$base day",strtotime($order['begin_time']))));
                        $data[$k]['order_id'] = $order['id'];
                        $data[$k]['which_period'] = $v['which_period'];
                        $data[$k]['begin_time'] = $begin_time;
                        $data[$k]['end_time'] = strtotime("+$lease_days day", $begin_time);
                        if($k==0){
                            $data[$k]['rent'] = sprintf("%.2f",$down_payment);
                        }else{
                            $data[$k]['rent'] = sprintf("%.2f",$v['lease_price']*$order['amount']);
                        }
                        $data[$k]['paid_rent'] = 0;
                        $data[$k]['create_time'] = time();
                        $data[$k]['pay_type'] = $order['pay_type'];
                        if($is_haubei == GoodsService::GOODS_SETMEAL_IS_HUABEI){//花呗
                            $data[$k]['pay_time'] = time();
                            $data[$k]['status']   = OrderLease::ORDER_LEASE_STATUS_PAID;
                            $data[$k]['alipay_trade_no'] =$alipay_trade_no;
                            $data[$k]['trade_no'] =$alipay_trade_no;
                            $data[$k]['paid_rent'] = sprintf("%.2f",$v['lease_price']*$order['amount']);
                        }
                    }
                }
            }elseif($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_MANAGER_CUSTOM){//后台自定义租期
                for ($i=0;$i<$order['month_total'];$i++){

                    $which_period = $i+1;

                    $rent_day=$order['lease_day']*$i;
                    $begin = strtotime('+'.$rent_day.'day',strtotime($order['begin_time']));
                    $begin_time = strtotime(date('Y-m-d H:i:s',$begin));

                    $data[$i]['order_id'] = $order['id'];
                    $data[$i]['which_period'] = $which_period;
                    $data[$i]['begin_time'] = $begin_time;
                    $data[$i]['end_time'] = $begin_time+$order['lease_day']*24*3600;
                    if($i==0){
                        $data[$i]['rent'] = sprintf("%.2f",$down_payment);
                    }else{
                        $data[$i]['rent'] = sprintf("%.2f",$order['lease_price']*$order['amount']);
                    }
                    $data[$i]['create_time'] = time();
                    $data[$i]['paid_rent'] = 0;
                    $data[$i]['pay_type'] = $order['pay_type'];

                }

            }

            Order::where('id',$order['id'])->update(['end_time'=>date('Y-m-d H:i:s',$data[$order['month_total']-1]['end_time'])]);

            if(!empty($data)){
                $res = OrderLease::insert($data);
                if($res){
                    return ['status'=>CommonService::HTTP_CODE_SUCCESS,'msg'=>'账单生成成功','data'=>$data];
                }else{
                    return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'账单生成失败','data'=>[]];
                }
            }else{
                return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'账单生成失败','data'=>[]];
            }
        }
    }

    //生成账单
    protected function createOrderLease($order,$is_haubei,$alipay_trade_no,$down_payment=0){
        if(!$down_payment>0){
            $down_payment=0;
        }
        if($this->where('order_id',$order['id'])->count() == 0){
            if($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_DAY){//按天租赁
                if($order['lease_time'] < 30){
                    $which_period = $order['lease_time'];
                    $begin = strtotime($order['begin_time']);
                    $begin_time = strtotime("+$which_period day",$begin);
                    $data[0]['order_id'] = $order['id'];
                    $data[0]['which_period'] = 1;
                    $data[0]['begin_time'] = $begin_time;
                    $data[0]['end_time'] = $begin_time+$order['lease_time']*24*3600;
                    $data[0]['rent'] = sprintf("%.2f",$order['lease_price'] * $order['lease_time']*$order['amount']+$down_payment);
                    $data[0]['create_time'] = time();
                    $data[0]['paid_rent'] = 0;
                    $data[0]['pay_type'] = $order['pay_type'];
                    if($is_haubei == GoodsService::GOODS_SETMEAL_IS_HUABEI){//花呗
                        $data[0]['pay_time'] = time();
                        $data[0]['status']   = OrderLease::ORDER_LEASE_STATUS_PAID;
                        $data[0]['alipay_trade_no'] =$alipay_trade_no;
                        $data[0]['trade_no'] =$alipay_trade_no;
                        $data[0]['paid_rent'] = sprintf("%.2f",$order['lease_price'] * $order['lease_time']*$order['amount']);
                    }
                }else{
                    for ($i=0;$i<$order['month_total'];$i++){
                        if($i+1 == ceil($order['lease_time']/30)){
//                          源代码有bug  $rent_day = $order['lease_time']%30;
                            $rent_day = $order['lease_time']-$i*30;
                        }else{
                            $rent_day = 30;
                        }

//                        $which_period = $i*30;
//                        $begin = strtotime($order['begin_time']) + ($which_period)*3600*24;

//                        $order['begin_time']='2023-01-30';
                        $which_period = $i;
                        $beginD=date('d',strtotime($order['begin_time']));
                        if($beginD>28){
                            $beginm_time=date('Y-m',strtotime($order['begin_time']));
                            $beginM=date('m',strtotime('+'.$i.'month',strtotime($beginm_time)));
                            $beginY=date('Y',strtotime('+'.$i.'month',strtotime($beginm_time)));

                            if($beginM=='02'&&$beginD>28){     //2月份最后一天
                                $begin_time = strtotime($beginY.'-'.$beginM.'-28');
                            }else if(in_array($beginM,['04','06','09','11'])&&$beginD>30){ //30天的最后一天
                                $begin_time = strtotime($beginY.'-'.$beginM.'-30');
                            }else{
                                $begin = strtotime('+'.$i.'month',strtotime($order['begin_time']));
                                $begin_time = strtotime(date('Y-m-d',$begin));
                            }
                        }else{
                            $begin = strtotime('+'.$i.'month',strtotime($order['begin_time']));
                            $begin_time = strtotime(date('Y-m-d',$begin));
                        }

                        $data[$i]['order_id'] = $order['id'];
                        $data[$i]['which_period'] = $i+1;
                        $data[$i]['begin_time'] = $begin_time;
                        $data[$i]['end_time'] = $begin_time+$which_period+$rent_day*24*3600;
                        if($i==0){
                            if($order['is_rent_choose'] == '1'){
                                //首月一元
                                $data[$i]['rent'] = 1+$down_payment;
                            }else if($order['is_rent_choose'] == '2'){
                                //首月五折
                                $data[$i]['rent'] = sprintf("%.2f",$order['lease_price']*$order['amount']*0.5+$down_payment);
                            }else{
                                $data[$i]['rent'] = sprintf("%.2f",$order['lease_price']*$order['amount']+$down_payment);
                            }

                        }else{
                            $data[$i]['rent'] = sprintf("%.2f",$order['lease_price']*$order['amount']);
                        }
                        $data[$i]['create_time'] = time();
                        $data[$i]['paid_rent'] = 0;
                        $data[$i]['pay_type'] = $order['pay_type'];
                        if($is_haubei == GoodsService::GOODS_SETMEAL_IS_HUABEI){//花呗
                            $data[$i]['pay_time'] = time();
                            $data[$i]['status']   = OrderLease::ORDER_LEASE_STATUS_PAID;
                            $data[$i]['alipay_trade_no'] =$alipay_trade_no;
                            $data[$i]['trade_no'] =$alipay_trade_no;
                            $data[$i]['paid_rent'] = sprintf("%.2f",$order['lease_price']*$rent_day*$order['amount']);
                        }
                    }
                }
            }elseif($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_MONTH){//按月租赁
                for ($i=0;$i<$order['month_total'];$i++){
                    $begin_time = strtotime(date('Y-m-d',strtotime("+$i months",strtotime($order['begin_time']))));
                    $data[$i]['order_id'] = $order['id'];
                    $data[$i]['which_period'] = $i+1;
                    $data[$i]['begin_time'] = $begin_time;
                    $data[$i]['end_time'] = strtotime("+1 months", $begin_time);
                    if($i==0){
                        $data[$i]['rent'] = sprintf("%.2f",$order['lease_price']*$order['amount']+$down_payment);
                    }else{
                        $data[$i]['rent'] = sprintf("%.2f",$order['lease_price']*$order['amount']);
                    }
                    $data[$i]['paid_rent'] = 0;
                    $data[$i]['create_time'] = time();
                    $data[$i]['pay_type'] = $order['pay_type'];
                    if($is_haubei == GoodsService::GOODS_SETMEAL_IS_HUABEI){//花呗
                        $data[$i]['pay_time'] = time();
                        $data[$i]['status']   = OrderLease::ORDER_LEASE_STATUS_PAID;
                        $data[$i]['alipay_trade_no'] =$alipay_trade_no;
                        $data[$i]['trade_no'] =$alipay_trade_no;
                        $data[$i]['paid_rent'] = sprintf("%.2f",$order['lease_price']*$order['amount']);
                    }
                }
            }elseif($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_CUSTOM){//自定义租期
                $lease = GoodsCustomRent::where([['goods_id',$order['goods_id']],['setmeal_id',$order['setmeal_id']],['spec_id',$order['spec_id']],['is_delete',CommonService::GOODS_IS_DELETE_NOT]])->select('id','spec_id','which_period','lease_days','withhold_cycle','lease_price')->get();
                $lease = $lease ? $lease->toArray() : [];
                if(!empty($lease)){
                    foreach ($lease as $k=>$v){
                        $lease_days = $v['lease_days'];
                        $base = $k * $lease_days;
                        $begin_time = strtotime(date('Y-m-d',strtotime("+$base day",strtotime($order['begin_time']))));
                        $data[$k]['order_id'] = $order['id'];
                        $data[$k]['which_period'] = $v['which_period'];
                        $data[$k]['begin_time'] = $begin_time;
                        $data[$k]['end_time'] = strtotime("+$lease_days day", $begin_time);
                        if($k==0){
                            $data[$k]['rent'] = sprintf("%.2f",$v['lease_price']*$order['amount']+$down_payment);
                        }else{
                            $data[$k]['rent'] = sprintf("%.2f",$v['lease_price']*$order['amount']);
                        }
                        $data[$k]['paid_rent'] = 0;
                        $data[$k]['create_time'] = time();
                        $data[$k]['pay_type'] = $order['pay_type'];
                        if($is_haubei == GoodsService::GOODS_SETMEAL_IS_HUABEI){//花呗
                            $data[$k]['pay_time'] = time();
                            $data[$k]['status']   = OrderLease::ORDER_LEASE_STATUS_PAID;
                            $data[$k]['alipay_trade_no'] =$alipay_trade_no;
                            $data[$k]['trade_no'] =$alipay_trade_no;
                            $data[$k]['paid_rent'] = sprintf("%.2f",$v['lease_price']*$order['amount']);
                        }
                    }
                }
            }elseif($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_MANAGER_CUSTOM){//后台自定义租期
                for ($i=0;$i<$order['month_total'];$i++){

                    $which_period = $i+1;

                    $rent_day=$order['lease_day']*$i;
                    $begin = strtotime('+'.$rent_day.'day',strtotime($order['begin_time']));
                    $begin_time = strtotime(date('Y-m-d H:i:s',$begin));

                    $data[$i]['order_id'] = $order['id'];
                    $data[$i]['which_period'] = $which_period;
                    $data[$i]['begin_time'] = $begin_time;
                    $data[$i]['end_time'] = $begin_time+$order['lease_day']*24*3600;
                    if($i==0){
                        $data[$i]['rent'] = sprintf("%.2f",$order['lease_price']*$order['amount']);
                    }else{
                        $data[$i]['rent'] = sprintf("%.2f",$order['lease_price']*$order['amount']);
                    }
                    $data[$i]['create_time'] = time();
                    $data[$i]['paid_rent'] = 0;
                    $data[$i]['pay_type'] = $order['pay_type'];
                }
            }

            Order::where('id',$order['id'])->update(['end_time'=>date('Y-m-d H:i:s',$data[$order['month_total']-1]['end_time'])]);



            if(!empty($data)){
                $res = OrderLease::insert($data);
                if($res){
                    return ['status'=>CommonService::HTTP_CODE_SUCCESS,'msg'=>'账单生成成功','data'=>$data];
                }else{
                    return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'账单生成失败','data'=>[]];
                }
            }else{
                return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'账单生成失败','data'=>[]];
            }
        }
    }



    //生成账单
    protected function createOtherOrderLease($order,$order_id,$order_data){
        if($this->where('order_id',$order_id)->count() == 0){

                    for ($i=0;$i<$order['month_total'];$i++){
                        if($i+1 == ceil($order['lease_time']/30)){
//                          源代码有bug  $rent_day = $order['lease_time']%30;
                            $rent_day = $order['lease_time']-$i*30;
                        }else{
                            $rent_day = 30;
                        }

                        $which_period = $i;
                        $beginD=date('d',strtotime($order['begin_time']));
                        if($beginD>28){
                            $beginm_time=date('Y-m',strtotime($order['begin_time']));
                            $beginM=date('m',strtotime('+'.$i.'month',strtotime($beginm_time)));
                            $beginY=date('Y',strtotime('+'.$i.'month',strtotime($beginm_time)));

                            if($beginM=='02'&&$beginD>28){     //2月份最后一天
                                $begin_time = strtotime($beginY.'-'.$beginM.'-28');
                            }else if(in_array($beginM,['04','06','09','11'])&&$beginD>30){ //30天的最后一天
                                $begin_time = strtotime($beginY.'-'.$beginM.'-30');
                            }else{
                                $begin = strtotime('+'.$i.'month',strtotime($order['begin_time']));
                                $begin_time = strtotime(date('Y-m-d',$begin));
                            }
                        }else{
                            $begin = strtotime('+'.$i.'month',strtotime($order['begin_time']));
                            $begin_time = strtotime(date('Y-m-d',$begin));
                        }

                        $data[$i]['order_id'] = $order_id;
                        $data[$i]['which_period'] = $i+1;
                        $data[$i]['begin_time'] = $begin_time;
                        $data[$i]['end_time'] = $begin_time+$which_period+$rent_day*24*3600;
                        $data[$i]['rent'] = $order_data[$i]['rent'];

                        $data[$i]['create_time'] = time();
                        $data[$i]['paid_rent'] = 0;
                        $data[$i]['pay_type'] = '1';

                    }

            if(!empty($data)){
                $res = OrderLease::insert($data);

                if($res){
                    return ['status'=>CommonService::HTTP_CODE_SUCCESS,'msg'=>'账单生成成功','data'=>$data];
                }else{
                    return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'账单生成失败','data'=>[]];
                }
            }else{
                return ['status'=>CommonService::HTTP_CODE_FAIL,'msg'=>'账单生成失败','data'=>[]];
            }
        }
    }


    protected function getOrderLease($order){
        $data = [];
        if($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_DAY){//按天租赁
            if($order['lease_time'] <= 30){
                $data['repayment_order_info.1.pay_date'] = (strtotime(date('Y-m-d',time()))+3600*12)*1000;
                $data['repayment_order_info.1.pay_money'] = sprintf("%.2f",$order['lease_price']*$order['amount'])*100;
                $data['repayment_order_info.1.trigger_immediately'] = 1;
            }else{
                for ($i=1;$i<=$order['month_total'];$i++){
                    if($i == ceil($order['lease_time']/30)){
                        $rent_day = $order['lease_time']%30;
                    }else{
                        $rent_day = 30;
                    }
                    //碎屏险
                    $is_insurance_choose = GoodsService::getGoodsInsurance($order['is_insurance_choose'],$order['is_insurance_choose_custom']);

                    $which_period = ($i-1)*30;
                    $begin = time() + ($order['start_date']+$which_period)*3600*24;
                    $begin_time = strtotime(date('Y-m-d',$begin));
                    $data['repayment_order_info.'.$i.'.pay_date'] = $begin_time*1000;
                    $data['repayment_order_info.'.$i.'.pay_money'] = sprintf("%.2f",$order['lease_price']*$order['amount'])*100;
                    if($i == 1){
                        if($order['is_rent_choose'] == '1'){
                            //首月一元
                            $first_rent = 1+$is_insurance_choose;
                        }else if($order['is_rent_choose'] == '2'){
                            //首月五折
                            $first_rent = sprintf("%.2f",$order['lease_price']*$order['amount']*0.5+$is_insurance_choose);
                        }else{
                            $first_rent = sprintf("%.2f",$order['lease_price']*$order['amount']+$is_insurance_choose);
                        }
                        $data['repayment_order_info.'.$i.'.pay_date'] = (strtotime(date('Y-m-d',time()))+3600*12)*1000;
                        $data['repayment_order_info.'.$i.'.trigger_immediately'] = 1;
                        $data['repayment_order_info.'.$i.'.pay_money'] = $first_rent*100;
                    }
                }
            }
        }elseif($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_MONTH){//按月租赁
            for ($i=1;$i<=$order['month_total'];$i++){
                $which_period = $i-1;
                $begin_time = strtotime(date('Y-m-d',strtotime("+$which_period months",strtotime($order['begin_time']))));
                $data['repayment_order_info.'.$i.'.pay_date'] = $begin_time*1000;
                if($i == 1){
                    $data['repayment_order_info.'.$i.'.pay_date'] = (strtotime(date('Y-m-d',time()))+3600*12)*1000;
                    $data['repayment_order_info.'.$i.'.trigger_immediately'] = 1;
                }
                $data['repayment_order_info.'.$i.'.pay_money'] = sprintf("%.2f",$order['lease_price']*$order['amount'])*100;
            }
        }elseif($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_CUSTOM){//自定义租期
            $lease = GoodsCustomRent::where([['goods_id',$order['goods_id']],['setmeal_id',$order['setmeal_id']],['spec_id',$order['spec_id']],['is_delete',CommonService::GOODS_IS_DELETE_NOT]])->select('id','spec_id','which_period','lease_days','withhold_cycle','lease_price')->get();
            $lease = $lease ? $lease->toArray() : [];
            if(!empty($lease)){
                foreach ($lease as $k=>$v){
                    $lease_days = $v['lease_days'];
                    $base = ($k+1) * $lease_days;
                    $sort = $k+1;
                    $begin_time = strtotime(date('Y-m-d',strtotime("+$base day",strtotime($order['begin_time']))));
                    $data['repayment_order_info.'.$sort.'.pay_date'] = $begin_time*1000;
                    if($v['which_period'] == 1){
                        $data['repayment_order_info.'.$sort.'.pay_date'] = (strtotime(date('Y-m-d',time()))+3600*12)*1000;
                        $data['repayment_order_info.'.$sort.'.trigger_immediately'] = 1;
                    }
                    $data['repayment_order_info.'.$sort.'.pay_money'] = sprintf("%.2f",$v['lease_price']*$order['amount'])*100;
                }
            }
        }elseif($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_MANAGER_CUSTOM){//自定义租期
            $lease = OrderLease::where('order_id',$order['id'])
                ->select(
                    'rent as needRepayAmount'
                    ,'rent as needRepayCapital'
                    ,'which_period'
                    ,'begin_time')
                ->get();
            $lease = $lease ? $lease->toArray() : [];
            if(!empty($lease)){
                $lease_days = $order['lease_day'];
                foreach ($lease as $k=>$v){
                    $base = $k * $lease_days;
                    $sort = $k+1;
                    $begin_time = strtotime(date('Y-m-d',strtotime("+$base day",strtotime($order['begin_time']))));
                    $data['repayment_order_info.'.$sort.'.pay_date'] = $begin_time*1000;
                    if($v['which_period'] == 1){
                        $data['repayment_order_info.'.$sort.'.pay_date'] = (strtotime(date('Y-m-d',time()))+3600*12)*1000;
                        $data['repayment_order_info.'.$sort.'.trigger_immediately'] = 1;
                    }
                    $data['repayment_order_info.'.$sort.'.pay_money'] = sprintf("%.2f",$v['needRepayAmount'])*100;
                }
            }
        }

        return $data;
    }

    //小程序租期详情
    protected function alipayOrderLease($order_id, $user_id)
    {
        $where[] = ['o.uid', $user_id];
        $where[] = ['o.id', $order_id];
        $order = Order::from('sp_order_2 as o')->where($where)
            ->leftjoin('sp_order_goods_2 as og', 'og.order_id', 'o.id')
            ->select('o.id', 'o.status', 'o.amount', 'o.begin_time', 'o.end_time', 'o.rent_total', 'o.month_total', 'o.month_paid',
                'og.goods_title', 'og.imgurl', 'og.setmeal_title')
            ->first();
        $order = $order ? $order->toArray() : [];
        if (!empty($order)) {
            $order['paid_rent_total'] = OrderLease::where([['order_id', $order_id], ['status', OrderLease::ORDER_LEASE_STATUS_PAID]])->sum('paid_rent');
            $order['lease_time'] = date("Y.m.d", strtotime($order['begin_time'])) . '-' . date("Y.m.d", strtotime($order['end_time']));
            $order_lease = $this->where('order_id', $order['id'])->select('id', 'which_period', 'rent', 'paid_rent', 'overdue_days', 'overdue_amount', 'begin_time', 'end_time', 'status', 'pay_time')->get();
            $order_lease = $order_lease ? $order_lease->toArray() : [];
            if (!empty($order_lease)) {
                foreach ($order_lease as $k => $v) {
                    $order_lease[$k]['begin_time'] = date('Y.m.d', $v['begin_time']);
                    $order_lease[$k]['end_time'] = date('Y.m.d', $v['end_time']);
                    if (!empty($v['pay_time'])) {
                        $order_lease[$k]['pay_time'] = date('Y.m.d H:i:s', $v['pay_time']);
                    }
                    $order_lease[$k]['lease_time'] = date("Y.m.d", $v['begin_time']) . '-' . date("Y.m.d", $v['end_time']);
                    $order_lease[$k]['this_rent'] = $v['rent'];
                    if ($v['rent'] + $v['overdue_amount'] > $v['paid_rent']) {
                        $order_lease[$k]['rent'] = bcsub($v['rent'] + $v['overdue_amount'], $v['paid_rent'], 2);
                    }
                }
            }
            $order['order_lease'] = $order_lease;
            return ['status' => CommonService::HTTP_CODE_SUCCESS, 'msg' => '获取成功', 'data' => $order];
        } else {
            return ['status' => CommonService::HTTP_CODE_FAIL, 'msg' => '订单不存在', 'data' => []];
        }
    }

    /**
     * 检测租期全部支付完毕修改订单状态
     * @param $order_id
     */
    public static function successPayToOrder($order_id)
    {
        $order = OrderGoods::where(['order_id' => $order_id])->select('pact_type')->first();
        $order = obToArray($order);
        if ($order) {
            //随租随还 固定租期 的订单
            if (in_array($order['pact_type'], [OrderGoods::PACT_TYPE_RENT_AND_RETURN, OrderGoods::PACT_TYPE_FIXED_LEASE_TERM])) {
                $lease = self::where(['order_id' => $order_id])->whereIn('status', [self::ORDER_LEASE_STATUS_NOPAY, self::ORDER_LEASE_STATUS_REFUNDED])->first();
                $lease = obToArray($lease);
                if (empty($lease)) {
                    //账单全部已支付 修改订单状态为待归还
                    Order::where(['id' => $order_id])->update(['status' => OrderService::ORDER_STATUS_TOBE_RETURNED]);
                }
            }
        }
    }

    /**
     * 更改某一期状态
     * @param $order_id
     */
    public static function successPayToOrderLease($order_id,$lease_id,$rent){

       return self::where(['id'=>$lease_id,'order_id'=>$order_id])->update(['paid_rent'=>$rent,'status'=>self::ORDER_LEASE_STATUS_PAID,'pay_time'=>time(),'pay_type'=>self::LEASE_PAY_TYPE_PREPAYMENT]);
    }

    /**
     * 订单列表获取账单数据
     * @param $orderId
     * @param $tradeNo
     * @return mixed
     */
    public static function getLeaseData($orderId,$tradeNo=''){
        $paid_rent = 0;//实付金额
        $settle_amount = 0;//结算金额
        $next = [];//下期租金
        $lease_log = [];//账单记录
        $orderLease = OrderLease::where(['order_id'=>$orderId])->select('id','which_period','rent','paid_rent','begin_time','settle_amount','status','pay_time','pay_type')
            ->orderBy('which_period', 'asc')
            ->get();
        $orderLease = obToArray($orderLease);
        //获取下月该归还的
//        $beginDate = date('Y-m-01 00:00:00', time());
//        $endDate = date('Y-m-d 23:59:59', strtotime("$beginDate +1 month -1 day"));
//        $paid_rent= OrderLease::where(['order_id'=>$orderId])->sum('paid_rent');
//        $settle_amount= OrderLease::where(['order_id'=>$orderId])->sum('settle_amount');
//        $OrderLeaseitem=OrderLease::where(['order_id'=>$orderId])->where('status','<>','1')->first();
//        $next[] = [
//                    'amount' => $OrderLeaseitem['rent'],
//                    'date' => dateDFormat($OrderLeaseitem['begin_time']),
//                ];

        foreach ($orderLease as $item){
            if(in_array($item['status'],[self::ORDER_LEASE_STATUS_PAID,self::ORDER_LEASE_STATUS_BUYOUT])){
                $paid_rent+=$item['paid_rent'];
//                $settle_amount+=$item['settle_amount'];
            }
            if(in_array($item['status'],[OrderLease::ORDER_LEASE_STATUS_NOPAY,OrderLease::ORDER_LEASE_STATUS_OVERDUE])){
                $next[] = [
                    'amount' => $item['rent'],
                    'date' => dateDFormat($item['begin_time']),
                ];
            }
        }
        $log = OtherWithholdLog::where(['order_no'=>$tradeNo,'status'=>OtherWithholdLog::STATUS_SUCCESS])->orderBy('id','desc')->first();
        $log = obToArray($log);
        if($log){
            $lease = OrderLease::where(['id'=>$log['lease_id']])->select('id','which_period','rent','paid_rent','begin_time','settle_amount','status','pay_time','pay_type')
                ->first();
            $lease = obToArray($lease);
            if($lease){
                $lease_log = [
                    'which_period'=>$lease['which_period'],
                    'rent'=>$lease['rent'],
                    'status'=>$lease['status'],
                    'pay_time'=>dateFormat($lease['pay_time']),
                    'pay_type'=>$lease['pay_type'],
                ];
            }
        }

//        $amount=ShopTrans::where(['order_id'=>$orderId])->where('remarks','结算价买断剩余租金')->value('amount');
//        if($amount){
//            $settle_amount+=$amount;
//        }

        $settle_amount=ShopTrans::where(['order_id'=>$orderId])->sum('amount');


//        foreach ($orderLease as $k=>$value){
//            //先查找退款的
//            if($value['status'] == self::ORDER_LEASE_STATUS_REFUNDED || $value['status'] == self::ORDER_LEASE_STATUS_BUYOUT){
//                $lease_log = [
//                    'which_period'=>$value['which_period'],
//                    'rent'=>$value['rent'],
//                    'status'=>$value['status'],
//                    'pay_time'=>dateFormat($value['pay_time']),
//                    'pay_type'=>$value['pay_type'],
//                ];
//                break;
//            }
//            //查找最后一个支付账单
//            if($value['status'] == self::ORDER_LEASE_STATUS_NOPAY){
//                if(isset($orderLease[$k-1])){
//                    $value = $orderLease[$k-1];
//                }
//                $lease_log = [
//                    'which_period'=>$value['which_period'],
//                    'rent'=>$value['rent'],
//                    'status'=>$value['status'],
//                    'pay_time'=>dateFormat($value['pay_time']),
//                    'pay_type'=>$value['pay_type'],
//                ];
//                break;
//            }
//        }
        $return['count']['paid_rent'] = sprintf("%.2f",$paid_rent);
        $return['count']['settle_amount'] = sprintf("%.4f",$settle_amount);
        $return['count']['next'] = $next ?  $next[0] : [];//下期租金
        $return['lease_log'] = $lease_log;//账单记录
        return $return;
    }

    /**
     * 手动扣款限制开关
     * @param $orderStatus //订单状态
     * @param $withholdStatus //扣款开关
     * @param $beginTime //预计扣款日
     * @param $LeaseStatus //账单状态
     * @param bool $isSeller // 是否是供应商后台
     * @return bool
     */
    public static function withholdLimit($orderStatus, $withholdStatus, $beginTime, $LeaseStatus, $isSeller = false)
    {
        $flag = false;
        if (
            in_array($orderStatus, OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))
//            && $withholdStatus == OrderLease::LEASE_WITHHOLD_STATUS_NO
            && in_array($LeaseStatus, [OrderLease::ORDER_LEASE_STATUS_NOPAY, OrderLease::ORDER_LEASE_STATUS_OVERDUE])
            && $beginTime < time()
        ) {
//            if($isSeller){
//                //供应商代扣
//                if($beginTime <= time()){
//                    $flag = true;
//                }
//            }else{
//                //管理后台代扣
//                $flag = true;
//            }
            $flag = true;
        }

        return $flag;
    }

    public static function getPayTime($order){
        if($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_DAY){//按天租赁
            if($order['lease_time'] <= 30){
                $which_period = $order['lease_time'];
                $begin = strtotime($order['begin_time']);
                $begin_time = strtotime("+$which_period day",$begin);
                $data[0]['which_period'] = 1;
                $data[0]['begin_time'] = $begin_time;
                $data[0]['rent'] = sprintf("%.2f",$order['lease_price'] * $order['lease_time']*$order['amount']);
            }else{
                for ($i=0;$i<$order['month_total'];$i++){
                    if($i+1 == ceil($order['lease_time']/30)){
                        $rent_day = $order['lease_time']%30;
                    }else{
                        $rent_day = 30;
                    }
                    $which_period = $i*30;
                    $begin = strtotime($order['begin_time']) + ($which_period)*3600*24;
                    $begin_time = strtotime(date('Y-m-d',$begin));
                    $data[$i]['which_period'] = $i+1;
                    $data[$i]['begin_time'] = $begin_time;
                    $data[$i]['rent'] = sprintf("%.2f",$order['lease_price']*$rent_day*$order['amount']);
                }
            }
        }elseif($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_MONTH){//按月租赁
            for ($i=0;$i<$order['month_total'];$i++){
                $begin_time = strtotime(date('Y-m-d',strtotime("+$i months",strtotime($order['begin_time']))));
                $data[$i]['which_period'] = $i+1;
                $data[$i]['begin_time'] = $begin_time;
                $data[$i]['rent'] = sprintf("%.2f",$order['lease_price']*$order['amount']);
            }
        }elseif($order['lease_set'] == GoodsService::GOODS_RENT_TYPE_CUSTOM){//自定义租期
            $lease = GoodsCustomRent::where([['goods_id',$order['goods_id']],['setmeal_id',$order['setmeal_id']],['spec_id',$order['spec_id']],['is_delete',CommonService::GOODS_IS_DELETE_NOT]])->select('id','spec_id','which_period','lease_days','withhold_cycle','lease_price')->get();
            $lease = $lease ? $lease->toArray() : [];
            if(!empty($lease)){
                foreach ($lease as $k=>$v){
                    $lease_days = $v['lease_days'];
                    $base = $k * $lease_days;
                    $begin_time = strtotime(date('Y-m-d',strtotime("+$base day",strtotime($order['begin_time']))));
                    $data[$k]['which_period'] = $v['which_period'];
                    $data[$k]['begin_time'] = $begin_time;
                    $data[$k]['rent'] = sprintf("%.2f",$v['lease_price']*$order['amount']);
                }
            }
        }
        return $data;
    }

    //编辑每期租金-订单编辑数据
    protected function editLeaseRents($request)
    {
        $order_id = $request['orderId'];

        $this->where("order_id",$order_id)->delete();

        $order = Order::from('sp_order_2 as o')->where('o.id',$order_id)
                ->leftjoin('sp_order_goods_2 as og','o.id','og.order_id')
                ->select('o.id','o.rent_total','o.month_total','o.amount','o.begin_time','o.end_time','o.pay_type'
                    ,'og.lease_price','og.lease_time','og.setmeal_foregift','og.lease_set','og.lease_day','o.is_insurance_choose','o.is_insurance_choose_custom','o.is_rent_choose')
                ->first();
        $order = $order ? $order->toArray() : [];

        if(isset($request['down_payment'])&&$request['down_payment']>0){
            $res = OrderLease::createManageOrderLease($order,GoodsService::GOODS_SETMEAL_NO_HUABEI,'',$request['down_payment']);
        }else{
            $res = OrderLease::createOrderLease($order,GoodsService::GOODS_SETMEAL_NO_HUABEI,'',$request['down_payment']);
        }

    }

    //获取每期租金-订单编辑数据
    protected function getLeaseRent($orderId)
    {
        $select = array('order_id', 'rent');
        $data = $this
            ->select($select)
            ->where("order_id",$orderId)
            ->orderBy('id','desc')
            ->first();
        $data = $data ? $data->toArray() : [];
        return $data;
    }


    //分销商订单租期
    protected function saleOrderLeaseDetail($order_id){
        $order_lease_num = $this->where('order_id',$order_id)
                                ->selectRaw('
                                        SUM(reward_amount) as reward_amount_num,
                                        COUNT(id) as paid_num
                                    ')
                                ->first();
        $order_lease_num = $order_lease_num ? $order_lease_num->toArray() : [];

        $orderLease = [];

        if(!empty($order_lease_num) && $order_lease_num['paid_num']>0){
            $order_lease_paid_num = $this->where('order_id',$order_id)->where('status',OrderLease::ORDER_LEASE_STATUS_PAID)
                                ->where('reward_type',OrderLease::ORDER_LEASE_SETTLE_STATUS_YES)
                                ->selectRaw('
                                        SUM(reward_amount) as reward_amount_num,
                                        COUNT(id) as paid_num
                                    ')
                                ->first();
            $order_lease_paid_num = $order_lease_paid_num ? $order_lease_paid_num->toArray() : [];
            // dd($order_lease_paid_num);
            //ORDER_LEASE_STATUS_OVERDUE
            $orderLease['orderLease'] = $order_lease_paid_num['paid_num'].'/'.$order_lease_num['paid_num'];

            $order_lease = $this->where('order_id',$order_id)->where('status',OrderLease::ORDER_LEASE_STATUS_OVERDUE)->select('begin_time')->orderBy('id','asc')->first();
            $order_lease = $order_lease ? $order_lease->toArray() : [];
            if(!empty($order_lease)){
                $orderLease['overdue_time'] = date('Y-m-d H:i:s',$order_lease['begin_time']);
            }

            $orderLease['paid_num_rent'] = $order_lease_paid_num['reward_amount_num']; //已结算租金

            //查询第一期是否结算，结算了就会同时结算固定金额
            if($order_lease_paid_num['paid_num'] >0){
                $orderLease['reward'] = 1; //已结算固定
            }else{
                $orderLease['reward'] = 0;
            }

            $orderLease['reward_amount'] = $order_lease_num['reward_amount_num'];//总租金

        }else{
            $orderLease['orderLease'] = '0/0';
            $orderLease['overdue_time'] = '';
            $orderLease['paid_num_rent'] = '0.00';
            $orderLease['reward'] = 0;
            $orderLease['reward_amount'] = '0.00';
        }
        return $orderLease;
    }


    //租赁宝租期数据返回


}
